import { useEffect } from "react";
import { Space, Table, Form, Input, Popconfirm } from "antd";
import { ButtonGroup, Card as SemiCard, Button } from "@douyinfe/semi-ui";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { IconDelete, IconEdit, IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { message } from "antd";

const { Column } = Table;

const GatewayTypePage = () => {
    const { windowInnerHeight, graphqlFetchPlatform } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        types: [],
    });

    const loadData = async () => {
        state.loading = true;
        let query = `query MyQuery { a: allOrganizationGatewayTypes { totalCount nodes { creater isSystem isDefault name notes updater status submiter examiner isStop } } }`;
        let res = await graphqlFetchPlatform({ query, variables: {} });
        state.types = res?.a?.nodes || [];
        state.loading = false;
    };

    useEffect(() => {
        loadData();
    }, []);

    const openAddModal = () => {
        setModalTitle("添加组织网关类型");
        setModalVisible(true);
        setModalWidth(500);
        setModalComponent(<Add reloadData={loadData} />);
    };

    const openEditModal = (record) => {
        setModalTitle("编辑组织网关类型信息");
        setModalVisible(true);
        setModalWidth(500);
        setModalComponent(<Edit reloadData={loadData} record={record} />);
    };

    const handleIsStop = async (record) => {
        state.submitLoading = true;
        let query = `mutation MyMutation($name: String!, $isStop: Boolean!) {
            updateOrganizationGatewayTypeByName( input: {organizationGatewayTypePatch: {isStop: $isStop}, name: $name} ) { clientMutationId }
        }`;
        let res = await graphqlFetchPlatform({ query, variables: { name: record.name, isStop: !record.isStop } });
        if (res) {
            message.success("成功删除组织网关类型信息");
            loadData();
        }
        state.submitLoading = false;
    };

    const handleStatus = async (record) => {
        state.submitLoading = true;
        let query = `mutation MyMutation($name: String!, $status: Boolean!, $examiner: JSON!) {
            updateOrganizationGatewayTypeByName( input: {organizationGatewayTypePatch: {status: $status, examiner: $examiner}, name: $name} ) { clientMutationId }
        }`;
        let res = await graphqlFetchPlatform({
            query,
            variables: {
                name: record.name,
                status: !record.status,
                examiner: {
                    uuid: baseInfo.uuid,
                    name: baseInfo.realName,
                    time: new Date().getUTCTime(),
                },
            },
        });
        if (res) {
            message.success("成功删除组织网关类型信息");
            loadData();
        }
        state.submitLoading = false;
    };

    const handleDelete = async (record) => {
        if (record.isSystem) return message.warning("是系统默认，不能删除");
        // 要判断是否被引用
        state.submitLoading = true;
        let query = `query MyQuery($contains: [String]) { a: allApplications(filter: { appGwty: { contains: $contains } }) { totalCount } }`;
        let res = await graphqlFetchPlatform({ query, variables: { contains: record.name } });
        if (res) {
            if (res.a?.totalCount > 0) {
                message.warning("该网关类型已经有应用引用了，不能删除");
                state.submitLoading = false;
                return;
            }
            query = `mutation MyMutation($name: String!) { deleteOrganizationGatewayTypeByName(input: {name: $name}) { clientMutationId } }`;
            res = await graphqlFetchPlatform({ query, variables: { name: record.name } });
            if (res) {
                message.success("成功删除组织网关类型信息");
                loadData();
            }
        }
        state.submitLoading = false;
    };

    const renderIsStop = (_, r, i) => (
        <Popconfirm
            title="确定要更改组织网关类型停用状态吗?"
            okButtonProps={{ loading: state.submitLoading }}
            placement="topRight"
            onConfirm={() => handleIsStop(r)}
        >
            <Button theme="borderless" type={_ ? "danger" : "primary"} disabled={r.isSystem}>
                {_ ? "已停用" : "正常"}
            </Button>
        </Popconfirm>
    );

    const renderState = (_, r, i) => (
        <Popconfirm
            title="确定要更改组织网关类型审核状态吗?"
            okButtonProps={{ loading: state.submitLoading }}
            placement="topRight"
            onConfirm={() => handleStatus(r)}
        >
            <Button theme="borderless" type={_ ? "primary" : "danger"} disabled={r.isSystem}>
                {_ ? "已审核" : "待审核"}
            </Button>
        </Popconfirm>
    );

    const renderOperate = (_, r, i) => (
        <Space>
            {!r.isSystem && <Button theme="borderless" icon={<IconEdit />} onClick={() => openEditModal(r)} />}
            {!r.isSystem && (
                <Popconfirm
                    title="确定要删除组织网关类型信息吗?"
                    okButtonProps={{ loading: state.submitLoading }}
                    placement="topRight"
                    onConfirm={() => handleDelete(r)}
                >
                    <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                </Popconfirm>
            )}
        </Space>
    );

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织网关类型</span>}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={openAddModal} />
                        <Button icon={<IconRefresh />} onClick={loadData} />
                    </ButtonGroup>
                }
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
            >
                <Table
                    loading={state.loading}
                    dataSource={state.types}
                    rowKey="name"
                    bordered
                    size="small"
                    pagination={false}
                    scroll={{ y: cardBodyHeight - 40 }}
                >
                    <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                    <Column title="类型名称" dataIndex="name" align="center" width={160} />
                    <Column title="备注" dataIndex="notes" align="left" />
                    <Column title="是否系统默认" dataIndex="isSystem" align="center" width={120} render={(_, r, i) => (_ ? "系统默认" : "-")} />
                    <Column title="是否组织默认" dataIndex="isDefault" align="center" width={120} render={(_, r, i) => (_ ? "组织默认" : "-")} />
                    <Column title="提交组织" dataIndex="submiter" align="center" width={180} render={(_, r, i) => _?.name} />
                    <Column title="提交人" dataIndex="creater" align="center" width={80} render={(_, r, i) => _?.name} />
                    <Column title="提交时间" dataIndex="creater" align="center" width={140} render={(_, r, i) => (_?.time ? formatUTCTime(_.time) : "-")} />
                    <Column title="停用状态" dataIndex="isStop" align="center" width={100} render={renderIsStop} />
                    <Column title="审核状态" dataIndex="status" align="center" width={100} render={renderState} />
                    <Column title="审核人" dataIndex="examiner" align="center" width={100} render={(_, r, i) => _?.name} />
                    <Column title="操作" align="center" width={100} render={renderOperate} />
                </Table>
            </SemiCard>
        </div>
    );
};

const Add = ({ reloadData }) => {
    const { graphqlFetchPlatform } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const state = useReactive({
        submitLoading: false,
    });

    const onFinish = async (values) => {
        state.submitLoading = true;
        // 判断提交的名称是否已存在
        let query = `query MyQuery($name: String!) { a: organizationGatewayTypeByName(name: $name) { name } }`;
        let res = await graphqlFetchPlatform({ query, variables: values });
        if (res?.a?.name) {
            message.warning("组织网关类型名称已存在，请重新输入");
            state.submitLoading = false;
            return;
        }
        query = `mutation MyMutation($name: String!, $notes: String) {
            createOrganizationGatewayType( input: { organizationGatewayType: { name: $name, notes: $notes } } ) { clientMutationId }
        }`;
        res = await graphqlFetchPlatform({ query, variables: values });
        if (res) {
            message.success("成功添加组织网关类型信息");
            await reloadData();
            onCloseGlobalModal();
        }
        state.submitLoading = false;
    };

    return (
        <div style={{ padding: 10 }}>
            <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                <Form.Item label="类型名称" name="name" rules={[{ required: true, validator: nameValidator }]}>
                    <Input />
                </Form.Item>

                <Form.Item label="备注" name="notes" rules={[{ required: true, validator: notesValidator }]}>
                    <Input />
                </Form.Item>

                <div style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={state.submitLoading} type="primary" htmlType="submit">
                            提交
                        </Button>
                        <Button loading={state.submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

const Edit = ({ record, reloadData }) => {
    const { graphqlFetchPlatform } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const state = useReactive({
        submitLoading: false,
    });

    const onFinish = async (values) => {
        state.submitLoading = true;
        const query = `mutation MyMutation($name: String!, $notes: String!) {
            updateOrganizationGatewayTypeByName( input: { organizationGatewayTypePatch: { notes: $notes }, name: $name } ) { clientMutationId }
        }`;
        let res = await graphqlFetchPlatform({ query, variables: { name: record.name, ...values } });
        if (res) {
            message.success("成功添加组织网关类型信息");
            await reloadData();
            onCloseGlobalModal();
        }
        state.submitLoading = false;
    };

    return (
        <div style={{ padding: 10 }}>
            <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} initialValues={record}>
                <Form.Item label="备注" name="notes" rules={[{ required: true, validator: notesValidator }]}>
                    <Input />
                </Form.Item>

                <div style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={state.submitLoading} type="primary" htmlType="submit">
                            提交
                        </Button>
                        <Button loading={state.submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                            重置
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

const nameValidator = (rule, value) => {
    if (value && /^[a-z]{1,}$/.test(value)) {
        return Promise.resolve();
    } else {
        return Promise.reject("类型名称只能输入英文小写字母，至少1个字符");
    }
};

const notesValidator = (rule, value) => {
    if (value && validates.textArea(value)) {
        return Promise.resolve();
    } else {
        return Promise.reject("备注含有非法字条");
    }
};

export default GatewayTypePage;
